<template>
    <div class="register">
      <h2>注册</h2>
      <form @submit.prevent="handleRegister">
        <div class="input-group">
          <label for="username">用户名：</label>
          <input type="text" id="username" v-model="username" required />
        </div>
        <div class="input-group">
          <label for="password">密码：</label>
          <input type="password" id="password" v-model="password" required />
        </div>
        <div class="input-group">
          <label for="perName">姓名：</label>
          <input type="text" id="perName" v-model="perName" required />
        </div>
        <div class="input-group">
          <label for="email">邮箱：</label>
          <input type="email" id="email" v-model="email" required />
        </div>
        <div class="input-group">
          <label for="role">角色：</label>
          <select id="role" v-model="role" required>
            <option value="ADMIN">管理员</option>
            <option value="COMMON">普通用户</option>
            <option value="QUEST">访客</option>
          </select>
        </div>
        <button type="submit">注册</button>
      </form>
      <p v-if="error" class="error">{{ error }}</p>
    </div>
  </template>
  
  <script>
  import api from '@/api';
  
  export default {
    data() {
      return {
        username: '',
        password: '',
        perName: '',
        email: '',
        role: '',
        error: ''
      };
    },
    methods: {
      async handleRegister() {
        const dataToSend = {
            username: this.username,
            password: this.password,
            perName: this.perName,
            email: this.email,
            role: this.role
          };
        try {
          console.log(dataToSend);
          
          const response = await api.Register(dataToSend);
  
          if (response.data.success) {
            alert('注册成功！');
            // 清空表单
            this.username = '';
            this.password = '';
            this.perName = '';
            this.email = '';
            this.role = '';
            this.error = '';
          } else {
            this.error = response.data.message;
          }
        } catch (error) {
          this.error = '注册失败，请稍后再试。';
        }
      }
    }
  };
  </script>
  
  <style scoped>
  .register {
    max-width: 400px;
    margin: 50px auto;
    padding: 20px;
    border: 1px solid #ccc;
    border-radius: 5px;
  }
  
  .input-group {
    margin-bottom: 15px;
  }
  
  .error {
    color: red;
  }
  </style>